/**
 * ReportGear(2011)
 */
package com.reportgear.designer.view;

import java.awt.BorderLayout;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;

import javax.swing.JOptionPane;
import javax.swing.JPanel;

import com.reportgear.core.data.SalaryHelper;
import com.reportgear.designer.view.menu.GridPopupMenu;
import com.reportgear.report.context.ReportContext;
import com.reportgear.report.core.api.idname.IdName;
import com.reportgear.report.model.ReportModel;
import com.reportgear.report.model.SalaryReportModel;
import com.reportgear.report.view.JWorksheet;

/**
 * 工作区视图
 * 
 * @version 1.0 2011-4-17
 * @author <a herf="lexloo@gmail.com">lexloo</a>
 * @since Report 1.0
 */
public class WorkbenchView extends JPanel implements PropertyChangeListener {
	/**
	 * UID
	 */
	private static final long serialVersionUID = 2846447267601023999L;
	private JWorksheet worksheet;
	private ReportModel reportModel;

	public WorkbenchView() {
		this.setLayout(new BorderLayout());
		this.reportModel = new SalaryReportModel();

		this.worksheet = this.createJWorksheet();
		this.add(this.worksheet, BorderLayout.CENTER);

		ReportContext.INSTANCE.setCurrentWorkSheet(this.worksheet);
	}

	@Override
	public void propertyChange(PropertyChangeEvent evt) {
		if (evt.getPropertyName().equals("currReport")) {
			@SuppressWarnings("unchecked")
			int reportId = ((IdName<Integer>) evt.getNewValue()).getId();

			this.loadReport(reportId);
		}
	}

	private JWorksheet createJWorksheet() {
		JWorksheet sheet = new JWorksheet(this.reportModel);
		sheet.setGridActionMenu(new GridPopupMenu());

		return sheet;
	}

	/**
	 * 加载报表模板
	 * 
	 * @param reportId
	 *            报表模板
	 */
	public void loadReport(int reportId) {
		if (this.worksheet != null) {
			this.remove(this.worksheet);
			this.worksheet = null;
			this.reportModel = null;
		}

		if (reportId != 0) {
			String template = SalaryHelper.INSTANCE.loadTemplate(reportId);
			this.reportModel = new SalaryReportModel();
			this.reportModel.fromXmlString(template);
			this.reportModel.setId(reportId);
		}
		this.worksheet = this.createJWorksheet();

		this.add(this.worksheet);

		ReportContext.INSTANCE.setCurrentWorkSheet(this.worksheet);

		this.updateUI();
	}

	/**
	 * 保存报表
	 */
	public void saveReport() {
		SalaryReportModel rm = (SalaryReportModel) this.reportModel;

		int id = SalaryHelper.INSTANCE.saveTemplate(rm.toXmlString(), rm.getId(), rm.getScheme(), rm.getName());

		if (id == rm.getId()) {
			JOptionPane.showMessageDialog(this, "模板已保存!");
		}
	}
}
